package com.stu.vertx.hello.otherTest;



import cn.hutool.core.codec.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
 

public class CallableTest {
 
    /**
     * 将file文件转换成Byte数组
     * @param file 转换文件
     * @return Byte数组
     */
    public static byte[] getBytesByFile(File file) throws IOException {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        try {
            fis = new FileInputStream(file);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            byte[] data = bos.toByteArray();
            return data;
        } catch (Exception e) {

        } finally {
            if (fis != null){
                fis.close();
            }
            bos.close();
        }
        return null;
    }
 
    /**
     * @param bytes byte数组
     * @param fileRoute 文件路径
     * @param fileName 文件名
     */
    public static void upload(byte[] bytes,String fileRoute,String fileName) {
        try {
            File directory=new File(fileRoute);
            if (!directory.exists()){
                directory.mkdirs();
            }
            File file = new File(directory, fileName);
            BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(file.toPath()));
            bos.write(bytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void test1() throws IOException {
        String path="C:\\Users\\Lenovo\\Desktop\\工作\\共产党宣言.pdf";
        File file=new File(path);
        byte[] bytes=getBytesByFile(file);
        String fileBase64= Base64.encode(bytes);
        System.out.println(fileBase64);
    }
 
    public static void main(String[] args) throws IOException {
        test1();
    }
}